package com.lancoo.znbkxx.teacher.ui.activity

import android.annotation.SuppressLint
import android.os.Build
import android.os.Handler
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.tu.loadingdialog.LoadingDailog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.PaperTrailListAdapter
import com.lancoo.znbkxx.teacher.adapter.SchoolPaperListAdapter
import com.lancoo.znbkxx.teacher.adapter.SpacesItemDecoration
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.AibkPaperPreviewActivity
import com.lancoo.znbkxx.teacher.base.BaseActivity
import com.lancoo.znbkxx.teacher.model.OperationHelp
import com.lancoo.znbkxx.teacher.model.data.*
import com.lancoo.znbkxx.teacher.ui.fragment.PublishResultDialog
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.lancoo.znbkxx.teacher.widget.PublishPopupWindow
import com.lancoo.znbkxx.teacher.widget.SchoolPopupWindow
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

import kotlinx.android.synthetic.main.activity_paperlibrary.*
import kotlinx.android.synthetic.main.activity_paperlibrary.swipe_layout
import kotlinx.android.synthetic.main.activity_paperlibrary.tv_paper_num
import kotlinx.android.synthetic.main.activity_paperlibrary.tv_title
import java.util.stream.Collectors

/**
 *@author Admin
 *@date 2021/2/4
 *
 */
class PaperLibraryActivity : BaseActivity(), View.OnClickListener, BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemChildClickListener, SchoolPopupWindow.OnSelectedListener,
        TextView.OnEditorActionListener {
    private lateinit var adapter: SchoolPaperListAdapter
    private lateinit var viewModel: PaperViewModel
    private val paperList = mutableListOf<SchoolPaper>()
    private val classFlagList = mutableListOf<ClassFlag>()
    private var position: Int = 0
    private val paperLibraries = mutableListOf<PaperCatlog>()
    private var totalCount = 0
    private val filterPopupWindow by lazy {
        SchoolPopupWindow(this, this, this, paperLibraries)
    }
    private val publishWindow by lazy {
        PublishPopupWindow(classFlagList, this, this)
    }
    private val pusblishDialog by lazy {
        LoadingDailog.Builder(this).setMessage("发布中...").setCancelOutside(false)
                .setCancelable(false).create()
    }

    override fun setLayout(): Int {
        return R.layout.activity_paperlibrary
    }

    override fun isNeedToolBar(): Boolean {
        return false
    }

    override fun initView() {
        viewModel = ViewModelProvider(this).get(PaperViewModel::class.java)
        lifecycle.addObserver(viewModel)
        sbtn_back.setOnClickListener(this)
        tv_switch.text = "综合"
        tv_paper_num.text = "共0份试卷"
        iv_search.setOnClickListener(this)
        tv_switch.setOnClickListener(this)
        edt_search.setOnEditorActionListener(this)
        Handler().postDelayed({ tv_switch.performClick() }, 500)
        initRecyclerView()
        startObserve()
    }

    private fun initRecyclerView() {
        viewModel.pageNo.value = 1
        viewModel.pageSize.value = 10
        adapter = SchoolPaperListAdapter(paperList)
        adapter.onItemClickListener = this
        adapter.onItemChildClickListener = this
        adapter.emptyView = layoutInflater.inflate(R.layout.adapter_item_empty, null)
        rv.layoutManager = LinearLayoutManager(this)
        val map = hashMapOf<String, Int>()
        map[SpacesItemDecoration.TOP_SPACE] = DensityUtils.dp2px(this, 12f)
        val itemDecoration = SpacesItemDecoration(map)
        rv.addItemDecoration(itemDecoration)
        rv.adapter = adapter
        swipe_layout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                viewModel.pageNo.value = 1
                viewModel.pageSize.value = 10
                searchPaper()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (totalCount >= viewModel.pageSize.value!!) {
                    viewModel.pageSize.value = viewModel.pageSize.value!! + 10
                    searchPaper()
                } else {
                    swipe_layout.finishLoadMore()
                }
            }
        })
    }


    @SuppressLint("SetTextI18n", "NewApi")
    fun startObserve() {
        viewModel.schoolConfig.observe(this, Observer {
            paperLibraries.clear()
            paperLibraries.addAll(it)
        })
        viewModel.paperLibrary.observe(this, Observer {
            totalCount = it.Count
            loadingDialog.dismiss()
            tv_paper_num.text = "共${it.Count}份试卷"
            paperList.clear()
            paperList.addAll(it.List)
            adapter.setNewData(it.List)
            swipe_layout.finishRefresh()
            swipe_layout.setEnableLoadMore(viewModel.pageSize.value!! < it.Count)
            if (viewModel.pageSize.value!! == it.Count) {
                swipe_layout.finishLoadMoreWithNoMoreData()
            } else {
                swipe_layout.finishLoadMore()
            }
        })
        viewModel.success.observe(this, Observer {
            pusblishDialog.dismiss()
            if (it.ReleaseResult) {
                publishWindow.dismiss()
                val publishDialog = PublishResultDialog().apply {
                    arguments = bundleOf().apply {
                        putParcelableArrayList("release", it.ClassEffectiveList)
                    }
                }
                publishDialog.show(supportFragmentManager, "")
                OperationHelp.operationLog(1, this)
                searchPaper()
            } else {
                MyToast.showToast( "发布失败")
            }
        })
        viewModel.mClassFlag.observe(this, Observer {
            classFlagList.clear()
            classFlagList.addAll(it)
            publishWindow.setOnDismissListener { dismissAnimation() }
            publishWindow.showAtLocation(tv_title, Gravity.BOTTOM, 0, 0)
            showAnimation()
        })
        viewModel.mErrorMsg.observe(this, Observer {
            pusblishDialog.dismiss()
            MyToast.showToast(it)
        })
    }

    override fun onResume() {
        super.onResume()
        viewModel.getCatalog(CurrentUser.getToken(), CurrentUser.getUserID(), CurrentUser.getSchoolID())
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_search -> {
                if (iv_search.tag == "search") {
                    iv_search.tag = "close"
                    iv_search.setImageResource(R.drawable.ic_baseline_close_24)
                    edt_search.visibility = View.VISIBLE
                } else {
                    iv_search.tag = "search"
                    iv_search.setImageResource(R.mipmap.aibk_icon_search)
                    edt_search.visibility = View.GONE
                }
            }
            R.id.tv_switch -> {
                showAnimation()
                filterPopupWindow.setOnDismissListener { dismissAnimation() }
                filterPopupWindow.showAsDropDown(view_history, 0, 0)
            }
            R.id.sbtn_back -> finish()
            R.id.tv_reset -> {
                filterPopupWindow.resetValue()
                filterPopupWindow.dismiss()
                adapter.setNewData(null)
                tv_switch.text = "请选择试卷"
                tv_paper_num.text = "共0份试卷"
            }
            R.id.tv_done -> {
                if (filterPopupWindow.paperType.isEmpty()) {
                    MyToast.showToast("请选择至少选择一类试卷")
                    return
                }
                filterPopupWindow.dismiss()
                searchPaper()
            }
            R.id.iv_cancel -> publishWindow.dismiss()
            R.id.tv_publish -> {
                if (publishWindow.getEndTime() < publishWindow.getStartTime()) {
                    MyToast.showToast("结束时间不得小于开始时间")
                    return
                }
                release(position)
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.N)
    fun switchModel(schoolConfig: SchoolConfig): Map<String, List<RelatedArea>> {
        val list = schoolConfig.RelatedArea
        return list.stream().collect(Collectors.groupingBy(RelatedArea::Province))
    }

    private fun showAnimation() {
        val lp = window.attributes
        lp.alpha = 0.8f
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        window.attributes = lp
    }

    private fun dismissAnimation() {
        val lp = window.attributes
        lp.alpha = 1.0f
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        window.attributes = lp
    }

    private fun searchPaper() {
        loadingDialog.show()
        viewModel.getPaperList(viewModel.pageNo.value!!, viewModel.pageSize.value!!,
                filterPopupWindow.paperType, edt_search.text.toString())
    }

    private fun release(position: Int) {
        val paperId = paperList[position].PaperID
        val classList = classFlagList.filter { it.checked }
        if (classList.isNullOrEmpty()) {
            MyToast.showToast("请选择发布班级")
            return
        }
        pusblishDialog.show()
        viewModel.releaseAuditPaper("", Ext.GLOBAL_GRADE, CurrentUser.getToken(), mutableListOf(paperId),
                publishWindow.getStartTime(), publishWindow.getEndTime(), classList.toMutableList(),
                CurrentUser.getUserID(), CurrentUser.getSchoolID(), 5, 0,
                CurrentUser.getUserName())
    }

    override fun onSelect(position: Int, text: String) {
        when (position) {
            0 -> {
                tv_switch.text = text
                chip_a.visibility = View.GONE
                chip_b.visibility = View.GONE
                chip_c.visibility = View.GONE
            }
            1 -> {
                chip_a.visibility = View.VISIBLE
                chip_a.text = text
                chip_b.visibility = View.GONE
                chip_c.visibility = View.GONE
            }
            2 -> {
                chip_b.visibility = View.VISIBLE
                chip_b.text = text
                chip_c.visibility = View.GONE
            }
            3 -> {
                chip_c.visibility = View.VISIBLE
                chip_c.text = text
            }
        }
    }

    override fun onDestroy() {
        lifecycle.removeObserver(viewModel)
        super.onDestroy()
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (adapter) {
            is SchoolPaperListAdapter -> {
                val paperId = adapter.data[position].PaperID
                AibkPaperPreviewActivity.launch(this, paperId, "", false)
            }
        }
    }


    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (view?.id) {
            R.id.tv_publish -> {
                val paperId = paperList[position].PaperID
                this.position = position
                viewModel.getGradeClassWithPaperState(Ext.GLOBAL_GRADE, CurrentUser.getSchoolID(), "",
                        paperId, CurrentUser.getToken(), CurrentUser.getUserID())
            }
        }
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            searchPaper()
        }
        return false
    }
}